﻿//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.Mvc;

using ProjectBase.Core;
using ProjectBase.Core.Web;
using ProjectBase.Mvc;

namespace Survey.Filters
{
    public class Html5IEFixFilter : IResultFilter
    {
        #region IResultFilter Members
        public void OnResultExecuting(ResultExecutingContext filterContext) { }

        public virtual void OnResultExecuted(ResultExecutedContext filterContext)
        {
            // only final ViewResult
            if (filterContext.IsChildAction)
            {
                return;
            }

            // is it a ViewResult?
            var result = filterContext.Result as ViewResult;
            if (result.IsNull())
            {
                return;
            }

            var browser = filterContext.RequestContext.HttpContext.Request.Browser;
            if (!browser.Browser.IsEqual("IE"))
            {
                return;
            }

            int version;
            if (!browser.Version.TryParse(out version, CultureInfo.InvariantCulture)
                || version > 8)
            {
                return;
            }

            // Change result for IE 8 and older
            filterContext.HttpContext.Response.Filter = new ResponseStream(filterContext.HttpContext.Response.Filter);
        }

        #endregion

        protected class ResponseStream : MemoryStream
        {
            readonly Stream _stream;
            public ResponseStream(Stream stream)
            {
                _stream = stream;
            }

            public override void Write(byte[] buffer, int offset, int count)
            {
                //base.Write(buffer, offset, count);
                string html = System.Text.Encoding.Default.GetString(buffer);

                var html5 = new List<string> { "section", "aside", "nav", "article" };
                foreach (var element in html5)
                {
                    html = html.Replace("<{0}>".FormatWith(element), "<div class=\"{0}\" >".FormatWith(element));
                    html = html.Replace("<{0} class=\"".FormatWith(element), "<div class=\"{0} ".FormatWith(element));
                    html = html.Replace("<{0}".FormatWith(element), "<div");
                    html = html.Replace("</{0}>".FormatWith(element), "</div>");
                }


                byte[] outdata = System.Text.Encoding.Default.GetBytes(html);

                //write bytes to stream
                _stream.Write(outdata, 0, outdata.GetLength(0));
            }
        }
    }

}